﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileEdit")]
	public class ProfileEditController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);
			return View();
		}

		public async Task<JsonCamelCaseResult> GetData()
		{
			var sysUserMaster = await DbContext.SysUserMaster.AsNoTracking().FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);
			var sysUserMasterEn = await DbContext.SysUserMasterEn.AsNoTracking().FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);

			var isInternational = 0;
			if (Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En)
			{
				if (sysUserMasterEn != null)
				{
					// 画面英文，且英文表有信息，读取英文表信息
					isInternational = 1;
				}
			}
			else
			{
				// 画面中文，读取中文表信息
				isInternational = 2;
			}

			if (sysUserMaster != null)
			{				
				var passwordShow = StringExtension.Decrypt(sysUserMaster.Password);
				var result = new
				{
					Id = sysUserMaster.ID,
					UserName = sysUserMaster.UserName,
					Mail = sysUserMaster.Mail,
					Password = passwordShow,
					Language = sysUserMaster.Language,
					HeadImg = Path.GetFileName(sysUserMaster.HeadImg),

					FullName = isInternational == 1 ? sysUserMasterEn.FullName : isInternational == 2 ? sysUserMaster.FullName : string.Empty,
					FamilyName = isInternational == 1 ? sysUserMasterEn.FamilyName : isInternational == 2 ? sysUserMaster.FamilyName : string.Empty,
					FirstName = isInternational == 1 ? sysUserMasterEn.FirstName : isInternational == 2 ? sysUserMaster.FirstName : string.Empty,
					Gender = sysUserMaster.Gender,
					Birthday = Utility.SetDate(sysUserMaster.Birthday, Request.Cookies["_culture"].Value),
					Call = isInternational == 1 ? sysUserMasterEn.Call : isInternational == 2 ? sysUserMaster.Call : null,
					Degree = sysUserMaster.Degree,
					Career = sysUserMaster.Career?.Split(ConstValues.chrSemicolon),
					OcisCode = sysUserMaster.OcisCode?.Split(ConstValues.chrSemicolon),
					CV = isInternational == 1 ? sysUserMasterEn.CV : isInternational == 2 ? sysUserMaster.CV : string.Empty,
					
					Affiliation = isInternational == 1 ? sysUserMasterEn.Affiliation : isInternational == 2 ? sysUserMaster.Affiliation : string.Empty,
					Department = isInternational == 1 ? sysUserMasterEn.Department : isInternational == 2 ? sysUserMaster.Department : string.Empty,
					Address = isInternational == 1 ? sysUserMasterEn.Address : isInternational == 2 ? sysUserMaster.Address : string.Empty,
					ZipCode = sysUserMaster.ZipCode,
					Country = sysUserMaster.Country,
					State = sysUserMaster.StateStr,
					City = sysUserMaster.CityStr,
					Telephone = sysUserMaster.Telephone,
					Mobile = sysUserMaster.Mobile,

					InvoiceTitle = sysUserMaster.InvoiceTitle,
					TaxNum = sysUserMaster.TaxNum,
					AddressAndTel = sysUserMaster.AddressAndTel,
					Bank = sysUserMaster.Bank,
					BankAccount = sysUserMaster.BankAccount,
				};

				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Edit(SysUserMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var sysUserMaster = await DbContext.SysUserMaster.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);

			if (sysUserMaster == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			if (model.HeadImgFile != null)
			{
				if (model.HeadImgFile.ContentLength > ConstValues.PicMaxLength)
				{
					string errorMessage = Resources.MsgPicOverflowError;
					return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
							JsonRequestBehavior.AllowGet);
				}
				
				string folder = ConstValues.UserHeadImg;
				string pfolder = Server.MapPath(ConstValues.UserHeadImg);
				string fileName = ConstValues.TableId.SysUserMaster + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyyMMdd") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.HeadImgFile.FileName);
				model.HeadImgFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.HeadImgFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				sysUserMaster.HeadImg = model.HeadImgFilePath;
			}
			
			using (var transaction = DbContext.Database.BeginTransaction())
			{
				#region 保存公共信息
				sysUserMaster.Password = StringExtension.Encrypt(model.Password?.Trim());
				sysUserMaster.Language = model.Language;
				sysUserMaster.Birthday = model.Birthday;
				sysUserMaster.ZipCode = model.ZipCode?.Trim();
				sysUserMaster.IsLocked = false;
				sysUserMaster.PasswordFailed = ConstValues.intZero;
				sysUserMaster.HasUpdate = true;
				sysUserMaster.Status = ConstValues.Status.正常;
				sysUserMaster.Updater = LoginUser.UserName;
				sysUserMaster.UpdateDate = DateTime.Now;
				sysUserMaster.UpdateIP = LoginUser.IP;

				if (!string.IsNullOrWhiteSpace(model.InvoiceTitle))
				{
					sysUserMaster.InvoiceTitle = model.InvoiceTitle;
					sysUserMaster.TaxNum = model.TaxNum;
					sysUserMaster.AddressAndTel = model.AddressAndTel;
					sysUserMaster.Bank = model.Bank;
					sysUserMaster.BankAccount = model.BankAccount;
				}
				#endregion

				if (Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En)
				{
					#region 保存英文表信息
					var sysUserMasterEn = await DbContext.SysUserMasterEn.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);
					if (sysUserMasterEn != null)
					{
						sysUserMasterEn.FullName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
								Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(), ConstValues.Language.En);
						sysUserMasterEn.FamilyName = model.FamilyName?.Trim();
						sysUserMasterEn.FirstName = model.FirstName?.Trim();
						sysUserMasterEn.Gender = model.GenderStr == ConstValues.Gender.女 ? false : true;
						sysUserMasterEn.Call = model.Call;
						sysUserMasterEn.Degree = model.Degree;
						sysUserMasterEn.Career = string.Join(ConstValues.strSemicolon, model.Career);
						sysUserMasterEn.OcisCode = string.Join(ConstValues.strSemicolon, model.OcisCode);
						sysUserMasterEn.CV = model.CV?.Trim();
						sysUserMasterEn.Affiliation = model.Affiliation?.Trim();
						sysUserMasterEn.Department = model.Department?.Trim();
						sysUserMasterEn.Address = model.Address?.Trim();
						sysUserMasterEn.Country = model.Country;
						sysUserMasterEn.StateStr = model.State;
						sysUserMasterEn.CityStr = model.City;
						sysUserMasterEn.Telephone = model.Telephone?.Trim();
						sysUserMasterEn.Mobile = model.Mobile?.Trim();
						sysUserMasterEn.Status = ConstValues.Status.正常;
						sysUserMasterEn.Sort = ConstValues.DefaultSort;
						sysUserMasterEn.Updater = LoginUser.UserName;
						sysUserMasterEn.UpdateIP = LoginUser.IP;
						sysUserMasterEn.UpdateDate = DateTime.Now;
					}
					else
					{
						sysUserMasterEn = new SysUserMasterEn
						{
							ID = Utility.GetTableId(ConstValues.TableName.SysUserMasterEn),
							UserName = sysUserMaster.UserName,
							Mail = sysUserMaster.Mail,
							Status = ConstValues.Status.正常,
							Sort = ConstValues.DefaultSort,
							Creator = LoginUser.UserName,
							CreateIP = LoginUser.IP,
							CreateDate = DateTime.Now,
						};

						sysUserMasterEn.FullName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
								Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(), ConstValues.Language.En);
						sysUserMasterEn.FamilyName = model.FamilyName?.Trim();
						sysUserMasterEn.FirstName = model.FirstName?.Trim();
						sysUserMasterEn.Gender = model.GenderStr == ConstValues.Gender.女 ? false : true;
						sysUserMasterEn.Call = model.Call;
						sysUserMasterEn.Degree = model.Degree;
						sysUserMasterEn.Career = string.Join(ConstValues.strSemicolon, model.Career);
						sysUserMasterEn.OcisCode = string.Join(ConstValues.strSemicolon, model.OcisCode);
						sysUserMasterEn.CV = model.CV?.Trim();
						sysUserMasterEn.Affiliation = model.Affiliation?.Trim();
						sysUserMasterEn.Department = model.Department?.Trim();
						sysUserMasterEn.Address = model.Address?.Trim();
						sysUserMasterEn.Country = model.Country;
						sysUserMasterEn.StateStr = model.State;
						sysUserMasterEn.CityStr = model.City;
						sysUserMasterEn.Telephone = model.Telephone?.Trim();
						sysUserMasterEn.Mobile = model.Mobile?.Trim();

						DbContext.SysUserMasterEn.Add(sysUserMasterEn);
					}
					#endregion
				}
				else
				{
					#region 保存中文表信息
					sysUserMaster.FullName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
							Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(), ConstValues.Language.Cn);
					sysUserMaster.FamilyName = model.FamilyName?.Trim();
					sysUserMaster.FirstName = model.FirstName?.Trim();
					sysUserMaster.Gender = model.GenderStr == ConstValues.Gender.女 ? false : true;
					sysUserMaster.Call = model.Call;
					sysUserMaster.Degree = model.Degree;
					sysUserMaster.Career = string.Join(ConstValues.strSemicolon, model.Career);
					sysUserMaster.OcisCode = string.Join(ConstValues.strSemicolon, model.OcisCode);
					sysUserMaster.CV = model.CV?.Trim();
					sysUserMaster.Affiliation = model.Affiliation?.Trim();
					sysUserMaster.Department = model.Department?.Trim();
					sysUserMaster.Address = model.Address?.Trim();
					sysUserMaster.Country = model.Country;
					sysUserMaster.StateStr = model.State;
					sysUserMaster.CityStr = model.City;
					sysUserMaster.Telephone = model.Telephone?.Trim();
					sysUserMaster.Mobile = model.Mobile?.Trim();
					#endregion
				}

				Utility.SaveInvoiceInfo(LoginUser, new InvoiceModel
				{
					InvoiceTitle = model.InvoiceTitle,
					TaxNum = model.TaxNum,
					AddressAndTel = model.AddressAndTel,
					Bank = model.Bank,
					BankAccount = model.BankAccount,
				});

				await DbContext.SaveChangesAsync();
				transaction.Commit();
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEnData()
		{
			var sysUserMaster = await DbContext.SysUserMaster.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);
			var sysUserMasterEn = await DbContext.SysUserMasterEn.AsNoTracking().FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);
			if (sysUserMaster == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			var isInternational = 0;
			if (Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En)
			{
				// 画面英文，读取中文表信息
				isInternational = 2;
			}
			else
			{
				if (sysUserMasterEn != null)
				{
					// 画面中文，且英文表有信息，读取英文表信息
					isInternational = 1;
				}
			}

			var result = new
			{
				FullName = isInternational == 1 ? sysUserMasterEn.FullName : isInternational == 2 ? sysUserMaster.FullName : string.Empty,
				FamilyName = isInternational == 1 ? sysUserMasterEn.FamilyName : isInternational == 2 ? sysUserMaster.FamilyName : string.Empty,
				FirstName = isInternational == 1 ? sysUserMasterEn.FirstName : isInternational == 2 ? sysUserMaster.FirstName : string.Empty,
				Call = isInternational == 1 ? sysUserMasterEn.Call : isInternational == 2 ? sysUserMaster.Call : null,
				CV = isInternational == 1 ? sysUserMasterEn.CV : isInternational == 2 ? sysUserMaster.CV : string.Empty,
				Affiliation = isInternational == 1 ? sysUserMasterEn.Affiliation : isInternational == 2 ? sysUserMaster.Affiliation : string.Empty,
				Department = isInternational == 1 ? sysUserMasterEn.Department : isInternational == 2 ? sysUserMaster.Department : string.Empty,
				Address = isInternational == 1 ? sysUserMasterEn.Address : isInternational == 2 ? sysUserMaster.Address : string.Empty,
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> EditEn(SysUserMasterModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var sysUserMaster = await DbContext.SysUserMaster.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);

			if (sysUserMaster == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			if (Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En)
			{
				#region 保存中文表信息
				sysUserMaster.FullName = Utility.SetFullName(model.FamilyNameEN?.Trim(), model.FirstNameEN?.Trim(), ConstValues.Language.Cn);
				sysUserMaster.FamilyName = model.FamilyNameEN?.Trim();
				sysUserMaster.FirstName = model.FirstNameEN?.Trim();
				sysUserMaster.Call = model.CallEN;
				sysUserMaster.Address = model.AddressEN?.Trim();
				sysUserMaster.Affiliation = model.AffiliationEN?.Trim();
				sysUserMaster.Department = model.DepartmentEN?.Trim();
				sysUserMaster.CV = model.CVEN?.Trim();
				sysUserMaster.IsLocked = false;
				sysUserMaster.PasswordFailed = ConstValues.intZero;
				sysUserMaster.HasUpdate = true;
				sysUserMaster.Status = ConstValues.Status.正常;
				sysUserMaster.Updater = LoginUser.UserName;
				sysUserMaster.UpdateDate = DateTime.Now;
				sysUserMaster.UpdateIP = LoginUser.IP;
				#endregion
			}
			else
			{
				#region 保存英文表信息
				var sysUserMasterEn = await DbContext.SysUserMasterEn.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);
				if (sysUserMasterEn != null)
				{
					sysUserMasterEn.FullName = Utility.SetFullName(model.FamilyNameEN?.Trim(), model.FirstNameEN?.Trim(), ConstValues.Language.En);
					sysUserMasterEn.FamilyName = model.FamilyNameEN?.Trim();
					sysUserMasterEn.FirstName = model.FirstNameEN?.Trim();
					sysUserMasterEn.Call = model.CallEN;
					sysUserMasterEn.Address = model.AddressEN?.Trim();
					sysUserMasterEn.Affiliation = model.AffiliationEN?.Trim();
					sysUserMasterEn.Department = model.DepartmentEN?.Trim();
					sysUserMasterEn.CV = model.CVEN?.Trim();
					sysUserMasterEn.HasUpdate = true;
					sysUserMasterEn.Status = ConstValues.Status.正常;
					sysUserMasterEn.Sort = ConstValues.DefaultSort;
					sysUserMasterEn.Updater = LoginUser.UserName;
					sysUserMasterEn.UpdateIP = LoginUser.IP;
					sysUserMasterEn.UpdateDate = DateTime.Now;
				}
				else
				{
					sysUserMasterEn = new SysUserMasterEn
					{
						ID = Utility.GetTableId(ConstValues.TableName.SysUserMasterEn),
						UserName = sysUserMaster.UserName,
						Mail = sysUserMaster.Mail,
						HasUpdate = true,
						Status = ConstValues.Status.正常,
						Sort = ConstValues.DefaultSort,
						Creator = LoginUser.UserName,
						CreateIP = LoginUser.IP,
						CreateDate = DateTime.Now,
					};

					sysUserMasterEn.FullName = !string.IsNullOrEmpty(model.FullNameEN) ? model.FullNameEN?.Trim() :
							Utility.SetFullName(model.FamilyNameEN?.Trim(), model.FirstNameEN?.Trim(), ConstValues.Language.En);
					sysUserMasterEn.FamilyName = model.FamilyNameEN?.Trim();
					sysUserMasterEn.FirstName = model.FirstNameEN?.Trim();
					sysUserMasterEn.Gender = sysUserMaster.Gender;
					sysUserMasterEn.Call = model.CallEN;
					sysUserMasterEn.Degree = sysUserMaster.Degree;
					sysUserMasterEn.Career = sysUserMaster.Career;
					sysUserMasterEn.OcisCode = sysUserMaster.OcisCode;
					sysUserMasterEn.CV = model.CVEN?.Trim();
					sysUserMasterEn.Affiliation = model.AffiliationEN?.Trim();
					sysUserMasterEn.Department = model.DepartmentEN?.Trim();
					sysUserMasterEn.Address = model.AddressEN?.Trim();
					sysUserMasterEn.Country = sysUserMaster.Country;
					sysUserMasterEn.StateStr = sysUserMaster.StateStr;
					sysUserMasterEn.CityStr = sysUserMaster.CityStr;
					sysUserMasterEn.Telephone = sysUserMaster.Telephone;
					sysUserMasterEn.Mobile = sysUserMaster.Mobile;

					DbContext.SysUserMasterEn.Add(sysUserMasterEn);
				}
				#endregion
			}

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}		
	}
}